package com.example.opengldemo._camera_demo;

import android.content.Context;
import android.util.SparseArray;

import com.example.opengldemo._camera_demo.core.Renderer;
import com.example.opengldemo._camera_demo.handle.IHardStore;
import com.example.opengldemo._camera_demo.provider.CameraProvider;
import com.example.opengldemo._camera_demo.provider.ITextureProvider;

public class CameraCapture {
    public static final int KEY_CAMERA_MIN_WIDTH = 1;
    public static final int KEY_CAMERA_RATE = 2;
    public static final int KEY_OUTPUT_WIDTH = 3;
    public static final int KEY_OUTPUT_HEIGHT = 4;
    public static final int KEY_OUTPUT_PATH = 5;
    public static final int KEY_PREVIEW_WIDTH = 6;
    public static final int KEY_PREVIEW_HEIGHT = 7;

    private SparseArray<Float> propFloat;
    private SparseArray<String> propStr;
    public void setProperty(int key,float value){
        propFloat.put(key,value);
    }
    public void setProperty(int key,String value){
        propStr.put(key,value);
    }


    private Context context;
    private SurfaceShower shower;
    private SurfaceEncoder encoder;

    private ITextureProvider provider;
    private VideoSurfaceProcessor processor;
    private Renderer renderer;

    private IHardStore muxer;

    public CameraCapture(Context context){
        this.context = context;
        propFloat = new SparseArray<>();
        propStr = new SparseArray<>();
    }

    // 锁
    private Object showSurface;
    public void setPreviewSurface(Object surface){
        this.showSurface = surface;
        if(shower != null){
            shower.setSurface(surface);
        }
    }

    public void startPreview(){
        setPreviewSurface(showSurface);
        shower.open();
    }
    public void close(){
        processor.stop();
    }


    public void open(int id){
        //创建一个相机提供者
        provider = new CameraProvider();
        //设置相机的ID
        ((CameraProvider) provider).setDefaultCamera(id);
        //设置相机的狂高
        ((CameraProvider) provider).setCameraSize((int)(float)(propFloat.get(KEY_CAMERA_MIN_WIDTH,720f)),propFloat.get(KEY_CAMERA_RATE,1.7f));
        //设置一个surfaceshow 用于显示
        shower = new SurfaceShower();
        shower.setOutputSize((int)(float)(propFloat.get(KEY_PREVIEW_WIDTH,720.0f)),
                (int)(float)(propFloat.get(KEY_PREVIEW_HEIGHT,1280.0f)));
        // 绘制人
        processor = new VideoSurfaceProcessor();
        processor.setTextureProvider(provider);
        // 观察者
        processor.addObserver(shower);
        //设置绘制人
        setRenderer(renderer);
        //开始绘制
        processor.start();
    }

    public void setRenderer(Renderer renderer){
        this.renderer = renderer;
        if(processor != null){
            processor.setRenderer(renderer);
        }
    }
    public void stopPreview(){
        shower.close();
    }
}
